package top.eggcode.spring;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Title: HTTP 上下文工具
 * Description: TODO
 * Date:
 *
 * @author JiaQi Ding
 * @version 1.0
 */
public class HttpServletUtil {

    /**
     * 获取当前会话的 request
     *
     * @return request
     */
    public static HttpServletRequest getRequest() throws NullPointerException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            throw new NullPointerException();
        }
        return servletRequestAttributes.getRequest();
    }

    /**
     * 获取当前会话的 response
     *
     * @return response
     */
    public static HttpServletResponse getResponse() throws NullPointerException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            throw new NullPointerException();
        }
        return servletRequestAttributes.getResponse();
    }


    public static String getDomain() {
        HttpServletRequest request = getRequest();
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
    }

    public static String getOrigin() {
        HttpServletRequest request = getRequest();
        return request.getHeader("Origin");
    }


    public static String getHeaderAttribute(String key) {
        HttpServletRequest request = getRequest();
        return getHeaders().get(key.toLowerCase());
    }

    public static Map<String, String> getHeaders() {
        Map<String, String> map = new HashMap<>(20);
        Enumeration<String> headerNames = getRequest().getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = getRequest().getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>(20);
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = getRequest().getHeader(key);
            map.put(key, value);
        }
        return map;
    }
}
